<template>
  <div style="padding:10px">
    <el-card style="padding:10px;background:#EBEEF5">
      <div style="margin: 10px 0;width: 100%">
        <el-button type="primary" :icon="CirclePlus" @click="add">新增</el-button>
        <el-button type="danger" :icon="Remove" @click="Show" v-if="!isShow">批量删除</el-button>
        <el-button type="danger" :icon="Remove" @click="deleteBatch" v-if="isShow">删除</el-button>
        <el-button type="danger" :icon="CircleClose"  @click="Show" v-if="isShow">取消</el-button>
        <el-upload     action="http://localhost:9090/book/import"   :on-success="handleUploadSuccess"   :show-file-list=false   :limit="1"   accept='.xlsx'   style="display: inline-block; margin: 0 10px" >
          <el-button type="primary" :icon="Download">导入</el-button>
        </el-upload>
        <el-button :icon="Upload"  type="primary" @click="exportBook">导出</el-button>

        <el-input v-model="name" placeholder="请输入书名" style="width: 15%;margin: 0 10px 0 50px" clearable/>
        <el-input v-model="author" placeholder="请输入作者名" style="width: 15%;" clearable/>
        <el-button type="primary" :icon="Search" style="margin-left: 10px" @click="load">查询</el-button>
        <el-button type="primary" :icon="Refresh" style="margin-left: 10px" @click="reset">重置</el-button>
      </div>
    <el-table :data="tableData" :row-style="tableRowStyle" :cell-style="{'text-align':'center'}" :header-cell-style="{'text-align':'center'}"
              border resizable="true"  style="width: 100%"   @selection-change="handleSelectionChange">
      <el-table-column v-if="isShow" type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" sortable/>
      <el-table-column prop="name" label="名称"/>
      <el-table-column prop="price" label="价格"/>
      <el-table-column prop="author" label="作者"/>
      <el-table-column prop="createTime" label="出版日期"/>
      <el-table-column label="封面">
        <template #default="scope">
          <div>
            <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.cover"
                :preview-src-list="[scope.row.cover]"
                :initial-index="4"
                preview-teleported="true"
                hide-on-click-modal="true"
                fit="cover"
            />
          </div>
        </template>
      </el-table-column>

      <el-table-column style="display: flex" label="操作" width="300px">
        <template #default="scope">

          <el-button type="primary" @click="buy(scope.row.id)">购买
          </el-button>
        <el-button type="primary" :icon="Edit" @click="handleEdit(scope.row)">编辑
        </el-button>
        <el-popconfirm title="确定要删除吗?" @confirm="handleDelete(scope.row.id)">
          <template #reference>
            <el-button :icon="Remove" type="danger">删除</el-button>
          </template>
        </el-popconfirm>

      </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">

      <el-dialog
          v-model="dialogVisible"
          title="提示"
          width="30%"
      >
        <el-form label-width="120px">
          <el-form-item :model="form" label="名称">
            <el-input v-model="form.name" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item :model="form" label="价格">
            <el-input v-model="form.price" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item :model="form" label="作者">
            <el-input v-model="form.author" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item :model="form" label="出版日期">
            <el-date-picker v-model="form.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" style="width: 80%" clearable></el-date-picker>
          </el-form-item>
          <el-form-item :model="form" label="封面">
            <el-upload
                action="http://localhost:9090/file/upload"
                :on-success="filesUploadSucesss"
                ref="upload"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </span>
        </template>
      </el-dialog>
    </div>
    </el-card>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[2,5,10,20]"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        style="margin-top: 5px"
    >
    </el-pagination>
  </div>
</template>
<script>
// @ is an alias to /src
import request from "@/utils/request";
import { Edit,Remove,CirclePlus,Upload,Download,Search,Refresh,View,CircleClose } from '@element-plus/icons-vue';
export default {
  setup(){
    return{
      Edit,
      Remove,
      CirclePlus,
      Upload,
      Download,
      Search,
      Refresh,
      View,
      CircleClose
    }
  },
  name: 'Home',
  components: {Edit},
  data() {
    return {
      form: {},
      dialogVisible: false,
      currentPage: 1,
      total: 10,
      pageSize: 10,
      name:"",
      author: "",
      tableData: [],
      bookList:[],
      bookVis:false,
      isShow:false,
      ids:[],
      UserId:"",
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
    }
  },

  created() {
    this.load();
  },
  methods: {
    tableRowStyle({ row, rowIndex }) {
      return { background:'#F2F6FC', color: '#0052d9', 'font-weight': 600 }
    },
    reset(){
      this.name="";
      this.author="";
      this.load()
    },
    Show(){
      this.isShow=!this.isShow
    },
    deleteBatch(){
      if(!this.ids.length){
        this.$message.warning("请选择数据!")
        return
      }
      request.post("/book/del/batch",this.ids).then(res=>{
        if(res){
          this.$message.success("批量删除成功")
          this.load()
        }else{
          this.$message.error("批量删除失败")
        }
      })
    },
    handleSelectionChange(val){
      console.log(this.ids)
      this.ids=val.map(v => v.id)
    },
    handleUploadSuccess(res) {
      if (res.code === '200') {
        this.$message.success("导入成功")
        this.load()
      }
    },
    exportBook() {
      location.href = "http://localhost:9090/book/export";
    },

    showBooks(books){
      this.bookList=books;
      this.bookVis=true
    },

    load() {
      request.get("/book", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          name: this.name,
          author:this.author
        }
      }).then(res => {
        // console.log(res.code)
        console.log(res)
        this.tableData = res.records;
        this.UserId=this.user.id
        this.total = res.total
      })
    },
    buy(bookId){
      console.log(this.UserId)
      request.post("/orders/" + bookId+"/"+this.UserId).then(res=>{
        // console.log(res)
        if(res.code === '200'){
          this.$message.success("购买成功请前往订单页面支付!")
        }else {
          this.$message.error(res.msg)
          // this.$message.success("购买成功请前往订单页面支付!")
        }
      })
    },
    add() {
      this.dialogVisible = true;
      this.form = {}
      this.$refs["upload"].clearFiles()
    },
    save() {
      if (this.form.id) {
        request.post("/book/add", this.form).then(res => {
          console.log(res);
          if (res.code === '200') {
            this.$message({
              type: "success",
              message: "更新成功"
            })
          } else {
            this.$message({
              type: "error",
              message: "更新失败"
            })
          }
          this.load();
          this.dialogVisible = false
        });
      } else {
        request.post("/book/add", this.form).then(res => {
          console.log(res);
          if (res.code === '200') {
            this.$message({
              type: "success",
              message: "新增成功"
            })
          } else {
            this.$message({
              type: "error",
              message: "新增失败"
            })
          }
          this.load();
          this.dialogVisible = false
        })
      }
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true
      this.$refs["upload"].clearFiles()
    },
    handleSizeChange(pageSize) {
      this.pageSize=pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      this.currentPage=pageNum;
      this.load();
    },
    filesUploadSucesss(res){
      this.form.cover=res
    },
    handleDelete(id){

      request.delete("/book/"+id).then(res => {
        console.log(res.code)
        if (res){
          this.$message({
            type: "success",
            message: "删除成功"
          })
        }else {
          this.$message({
            type: "error",
            message: "删除失败"
          })
        }
        this.load()//重新加载
      });
    }
  }
}
</script>
